package com.woniuxy.authapp.service.impl;

import com.woniuxy.authapp.common.constant.AuthConstant;
import com.woniuxy.authapp.common.constant.MessageConstant;
import com.woniuxy.authapp.service.domain.SecurityUser;
import com.woniuxy.commons.util.Result;
import com.woniuxy.commons.util.WebUtil;
import com.woniuxy.userapp.client.BackgroundAccountClient;
import com.woniuxy.userapp.client.FrontAccountClient;
import com.woniuxy.userapp.client.param.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private FrontAccountClient frontAccountClient;
    @Autowired
    private BackgroundAccountClient backgroundAccountClient;




    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取是前台登录还是后台登录
        String client_id = WebUtil.getRequest().getParameter("client_id");
        UserInfo userInfo = new UserInfo();

        //后端登录正确
        if(AuthConstant.ADMIN_CLIENT_ID.equals(client_id)){
            Result<UserInfo> userInfoResult = backgroundAccountClient.BloadUserByUsername(userName);
            userInfo = userInfoResult.getData();
//            userDto = adminService.loadUserByUserName(nickName);
        }else if(AuthConstant.PORTAL_CLIENT_ID.equals(client_id)){
//            userDto = stuAndCoaService.loadUserByUserName(userName);
            Result<UserInfo> userInfoResult = frontAccountClient.FloadUserByUsername(userName);
            userInfo = userInfoResult.getData();

        }
        //未查询到此userDto
        if(userInfo == null){
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        //将request中的客户端id传给userDto
        userInfo.setClientId(client_id);
        SecurityUser securityUser = new SecurityUser(userInfo);
        //判断用户状态
        if(!securityUser.isEnabled()){
            throw new UsernameNotFoundException(MessageConstant.ACCOUNT_DISABLED);
        }else if(!securityUser.isAccountNonLocked()){
            throw new UsernameNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
        //账号过期
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
        //过期凭证
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }

        return securityUser;
    }
}
